package com.originskyseed.platform.user.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.ComplianceInspectionRules;
import com.originskyseed.platform.user.model.ComplianceInspectionRulesRelUser;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IComplianceInspectionRulesRelUserService;
import com.originskyseed.platform.user.service.IComplianceInspectionRulesService;
import com.originskyseed.platform.user.vo.request.ComplianceInspectionRulesRequestVO;

/**
 * 合规检查扣分规则表Controller类（OSI_COMPLIANCE_INSPECTION_RULES）
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/complianceInspectionRules")
@BaseLocaleResource(localeFileName = "i18n_user")
public class ComplianceInspectionRulesController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ComplianceInspectionRulesController.class);

	@DubboReference
	private IComplianceInspectionRulesService complianceInspectionRulesService;

	@DubboReference
	private IComplianceInspectionRulesRelUserService complianceInspectionRulesRelUserService;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/complianceInspectionRulesList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<ComplianceInspectionRules>> complianceInspectionRulesList(HttpServletRequest request) {
		BaseResponseBody<BasePage<ComplianceInspectionRules>> result = null;
		try {
			// 请求对象
			ComplianceInspectionRulesRequestVO requestVO = this.getParameterBean(ComplianceInspectionRulesRequestVO.class);

			// 分页查询
			BasePage<ComplianceInspectionRules> page = new BasePage<ComplianceInspectionRules>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.complianceInspectionRulesService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<ComplianceInspectionRules>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<ComplianceInspectionRules>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/complianceInspectionRulesSave.json", method = RequestMethod.POST)
	public BaseResponseBody<ComplianceInspectionRules> complianceInspectionRulesSave(HttpServletRequest request) {
		BaseResponseBody<ComplianceInspectionRules> result = null;
		try {
			// 当前登录信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 请求对象
			ComplianceInspectionRules complianceInspectionRules = this.getParameterBean(ComplianceInspectionRules.class);

			if (StringUtils.isNotBlank(complianceInspectionRules.getId())) {
				this.complianceInspectionRulesService.updateByPrimaryKey(complianceInspectionRules);
			} else {
				Integer integer = this.complianceInspectionRulesService.selectPriority();
				if(integer==null)
				{
					integer=1;
				}
				complianceInspectionRules.setPriority(integer + 1);
				complianceInspectionRules.setIsDel(0);
				complianceInspectionRules.setIsTop(0);
				complianceInspectionRules.setCreator(userInfo.getName());
				complianceInspectionRules.setCreatorId(userInfo.getId());
				this.complianceInspectionRulesService.insertSelective(complianceInspectionRules);
			}
			result = new BaseResponseBody<ComplianceInspectionRules>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), complianceInspectionRules);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<ComplianceInspectionRules>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/complianceInspectionRulesDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> complianceInspectionRulesDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.complianceInspectionRulesService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectComplianceInspectionRules.json", method = RequestMethod.POST)
	public BaseResponseBody selectComplianceInspectionRules(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			ComplianceInspectionRules complianceInspectionRules = this.complianceInspectionRulesService.selectByPrimaryKey(id);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), complianceInspectionRules);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 修改置顶信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateIsTop.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody updateIsTop(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer prority = this.complianceInspectionRulesService.selectPriority();

			ComplianceInspectionRules complianceInspectionRules = new ComplianceInspectionRules();
			complianceInspectionRules.setId(id);
			complianceInspectionRules.setIsTop(1);
			complianceInspectionRules.setPriority(prority + 1);

			this.complianceInspectionRulesService.updateIsTop(complianceInspectionRules);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 升序降序
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUpOrDown.json")
	@RequiredParams(names = { "id", "upOrDown", "prority" })
	public BaseResponseBody updateUpAndDown(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer upOrDown = this.getParameterInteger("upOrDown", null);

			// 查询出优先级
			ComplianceInspectionRules queryCompliance = this.complianceInspectionRulesService.selectByPrimaryKey(id);
			Integer priority = queryCompliance.getPriority();

			Map<String, Object> map = new HashMap<>();
			map.put("type", upOrDown);
			map.put("priority", priority);
			// 将另外一个升序或降序
			ComplianceInspectionRules complianceInspectionRules = this.complianceInspectionRulesService.selectComplianceByPrioritySort(map);

			ComplianceInspectionRules updateCompliance = new ComplianceInspectionRules();
			updateCompliance.setId(id);
			if (complianceInspectionRules != null) {
				updateCompliance.setPriority(complianceInspectionRules.getPriority());
				complianceInspectionRules.setPriority(priority);
			} else {
				// 等于0是升序 1是降序
				if (upOrDown == 0) {
					updateCompliance.setPriority(priority + 1);
				} else {
					updateCompliance.setPriority(priority - 1);
				}
			}

			if (complianceInspectionRules != null) {
				this.complianceInspectionRulesService.updatePrority(complianceInspectionRules, updateCompliance);
			} else {
				this.complianceInspectionRulesService.updateByPrimaryKeySelective(updateCompliance);
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_ORDER_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_ORDER_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 列表查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectComplianceInspectionRulesList.json", method = RequestMethod.POST)
	public BaseResponseBody<BasePage<ComplianceInspectionRules>> selectComplianceInspectionRulesList(HttpServletRequest request) {
		BaseResponseBody<BasePage<ComplianceInspectionRules>> result = null;
		try {
			// 当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 请求对象
			ComplianceInspectionRules queryComplianceInspectionRules = this.getParameterBean(ComplianceInspectionRules.class);
			queryComplianceInspectionRules.setPlatform(userInfo.getSourceSys());
			// 列表查询
			List<ComplianceInspectionRules> complianceInspectionRulesList = this.complianceInspectionRulesService.selectList(queryComplianceInspectionRules);

			// 查询用户看过的
			ComplianceInspectionRulesRelUser queryComplianceInspectionRulesRelUser = new ComplianceInspectionRulesRelUser();
			queryComplianceInspectionRulesRelUser.setUserId(userInfo.getId());
			List<ComplianceInspectionRulesRelUser> complianceInspectionRulesRelUserList = this.complianceInspectionRulesRelUserService.selectList(queryComplianceInspectionRulesRelUser);

			// 看过要修改的
			List<ComplianceInspectionRulesRelUser> insertList = new ArrayList<>();
			for (Iterator<ComplianceInspectionRules> it = complianceInspectionRulesList.iterator(); it.hasNext();) {
				ComplianceInspectionRules complianceInspectionRules = it.next();
				if (complianceInspectionRules.getTimes() != null && complianceInspectionRules.getTimes() == 1) {
					boolean flag = true;
					for (ComplianceInspectionRulesRelUser complianceInspectionRulesRelUser : complianceInspectionRulesRelUserList) {
						if (complianceInspectionRules.getId().equals(complianceInspectionRulesRelUser.getRuleId())) {
							flag = false;
							it.remove();
							break;
						}
					}
					if (flag) {
						ComplianceInspectionRulesRelUser complianceInspectionRulesRelUser = new ComplianceInspectionRulesRelUser();
						complianceInspectionRulesRelUser.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
						complianceInspectionRulesRelUser.setUserId(userInfo.getId());
						complianceInspectionRulesRelUser.setRuleId(complianceInspectionRules.getId());
						complianceInspectionRulesRelUser.setCreateTime(new Date());
						insertList.add(complianceInspectionRulesRelUser);
					}
				}
			}

			if (insertList.size() > 0) {
				this.complianceInspectionRulesRelUserService.insertBatch(insertList);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), complianceInspectionRulesList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}